package 代码随想录.链表.翻转链表;


public class Main {
    public ListNode reverseList(ListNode head) {
        //增加一个虚拟头节点
        ListNode listNode = new ListNode();
        listNode.next = null;
        ListNode p = head;
        while (p != null) {
            ListNode q = p.next;
            p.next = listNode.next;
            listNode.next = p;
            p = q;
        }
        return listNode.next;
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        Main code = new Main();
        ListNode node = code.reverseList(node1);
        while (node != null) {
            System.out.println(node.val);
            node = node.next;
        }
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
